import { reactive, ref, onMounted, onUnmounted, watchEffect } from 'vue'
import { mesLVTFeedingGetLvtInfo, mesLVTFeedingGetPageSet } from '@/api/mesApi'

let task = null

const killTask = () => {
  if (task) {
    clearInterval(task)
  }
}
/**
 * 创建表格数据
 * @param lvtFeedingDgData
 * @param context
 * @returns {Promise<void>}
 */
const createDgData = async ({
  lvtFeedingDgData,
  lvtFeedingDgLoading
}, context) => {
  await mesLVTFeedingGetPageSet({
    page: 100,
    row: 100
  }).then(function (res) {
    lvtFeedingDgData.length = 0
    lvtFeedingDgData.push(...res)
    lvtFeedingDgLoading.value = true
  }, function (e) {
    lvtFeedingDgLoading.value = true
    console.log(e)
  })
}
/**
 *
 * @param lvtInfo
 * @param rankList
 * @param ctx
 * @returns {Promise<void>}
 */
const createLvtInfo = async ({
  lvtInfo,
  rankList
}, ctx) => {
  await mesLVTFeedingGetLvtInfo().then((res) => {
    if (res) {
      /* 获取rankList */
      lvtInfo.rankList.length = 0
      lvtInfo.rankList.push(...res['上料优先级'])
      lvtInfo.rankList.length = lvtInfo.rankList.length > 4 ? 4 : lvtInfo.rankList.length
      /* 获取汇总数据 */
      lvtInfo.total.filed1 = res['LVT库存总数'] || 0
      lvtInfo.total.filed2 = res['未关闭的订单数量'] || 0
      lvtInfo.total.filed3 = res['未满足的订单成品总片数'] || 0
      lvtInfo.total.filed4 = res['行未满足的LVT总数(pcs)'] || 0
      lvtInfo.total.filed5 = res['行未满足的LVT满拖数'] || 0
      lvtInfo.total.filed6 = res['行未满足的LVT种类'] || 0
      /* 数据趋势图 */
      lvtInfo.chartData = [...res['订单成品对应LVT占比']]
      /* 可发货订单情况 */
      lvtInfo.finishedData = [...res['可发货订单']]
    }
  }, (e) => {
    console.log(e)
  })
}

const dataReady = ({
  ready,
  lvtFeedingDgData,
  lvtInfo,
  rankList,
  lvtFeedingDgLoading
}, ctx, { once }) => {
  setTimeout(async () => {
    ready.value = true
    await createDgData({
      lvtFeedingDgData,
      lvtFeedingDgLoading
    }, ctx)
    await createLvtInfo({
      lvtInfo,
      rankList
    }, ctx)
  }, 1000)
  if (!once && !task) {
    task = setInterval(async () => {
      await createDgData({
        lvtFeedingDgData,
        lvtFeedingDgLoading
      }, ctx)
      await createLvtInfo({
        lvtInfo,
        rankList
      }, ctx)
    }, 5000)
  }
}

export function LVTFeedingData (ctx, { once }) {
  /* 定义变量 */
  // 是否就绪
  const ready = ref(false)
  const lvtFeedingDgLoading = ref(false)
  // 表格数据
  const lvtFeedingDgData = reactive([])
  const lvtInfo = reactive({
    rankList: [],
    total: {},
    pieData: []
  })
  const rankList = reactive([])

  /* 挂载操作 */
  onMounted(() => dataReady({
    ready,
    lvtFeedingDgData,
    lvtFeedingDgLoading,
    lvtInfo,
    rankList
  }, ctx, { once }))
  onUnmounted(killTask)
  return {
    ready,
    lvtFeedingDgData,
    lvtInfo,
    rankList
  }
}
